import {
  DefineComponent,
  defineComponent,
  ExtractPropTypes,
  inject,
  watchEffect
} from "vue"
import { FiledPropsDefine } from "../types"
import SchemaItem from "../SchemaItem"
import { SchemaFormContextKey } from "../context"
import { isObject } from "../utils"

const schema = {
  type: "object",
  properties: {
    name: {
      type: "string"
    },
    age: {
      type: "number"
    }
  }
}

// const TypeHelperComponent = defineComponent({
//   props: FiledPropsDefine
// })
// type SchemaItemDefine = DefineComponent<typeof TypeHelperComponent>
type SchemaItemDefine = DefineComponent<typeof FiledPropsDefine>
export default defineComponent({
  name: "ObjectFiled",
  props: FiledPropsDefine,
  setup(props) {
    const context: { SchemaItem: SchemaItemDefine } | undefined = inject(
      SchemaFormContextKey
    )
    if (!context) {
      throw Error("SchemaForm should be used")
    }
    const handleObjectFieldChange = (k: string, v: string) => {
      const value: any = isObject(props.value) ? props.value : {}
      if (v === undefined) {
        delete value[k]
      } else {
        value[k] = v
      }
      props.onChange(value)
    }
    // watchEffect(() => {
    //   console.log(context.SchemaItem)
    // })
    return () => {
      const { schema, rootSchema, value } = props

      const { SchemaItem } = context

      const properties = schema.properties || {}

      const currentValue: any = isObject(value) ? value : {}

      return Object.keys(properties).map((k: string, index: number) => (
        <SchemaItem
          schema={properties[k]}
          rootSchema={rootSchema}
          value={currentValue[k]}
          key={index}
          onChange={(v: any) => handleObjectFieldChange(k, v)}
        />
      ))
    }
  }
})
